package com.flying.cms.request;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.flying.common.log.Logger;
import com.flying.common.util.Codes;
import com.flying.common.util.StringUtils;
import com.flying.framework.annotation.Service;
import com.flying.framework.context.ServiceContext;
import com.flying.framework.data.Data;
import com.flying.framework.data.DataUtils;
import com.flying.framework.data.JSONData;
import com.flying.framework.exception.AppException;
import com.flying.framework.module.LocalModule;
import com.flying.framework.request.AbstractRequestService;

@Service(value="XDoRequestService")
public class XDoRequestService extends AbstractRequestService{
	private final static Logger log = Logger.getLogger(XDoRequestService.class);

	@Override
	public void service(LocalModule module, String[] uris, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		final String service = this.serviceConfig.getConfig(uris[uris.length - 2]) == null?
				uris[uris.length - 2] : this.serviceConfig.getConfig(uris[uris.length - 2]); 
		final String method = uris[uris.length - 1];
		final String $value = req.getParameter("$value");
		Data request = DataUtils.convert(module, req);
		resp.setContentType("application/json;charset=UTF-8");

		if(ServiceContext.getContext() != null && ServiceContext.getContext().getPrincipal() != null) {
			request.put("creator", ServiceContext.getContext().getPrincipal().getName());
			request.put("updator", ServiceContext.getContext().getPrincipal().getName());
		}
		//
		Data data;
		try {
			data = module.invoke(service+":"+method, request);
		} catch (AppException e) {
			data = new Data(e);
		} catch (Exception e) {
			data = new Data(Codes.CODE, Codes.FAIL, Codes.MSG, e.getMessage());
			log.error("DoRequestSerice error", e);
		}
		if(!StringUtils.isEmpty($value)) data.put("$value", $value);
		JSONData result = new JSONData(data);
    	resp.getWriter().write(result.toJSONString());
	}
	
}
